<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20" class="el-row-table">
        <el-col :span="12"
          ><div class="grid-content bg-purple">
            <el-input
              placeholder="请输入内容"
              clearable
              v-model="queryInfo.name"
            >
              <el-button slot="append" icon="el-icon-search"></el-button>
            </el-input></div
        ></el-col>
        <el-col :span="4">
          <div class="grid-content bg-purple">
            <el-button type="primary" @click="addUserDialogVisible = true"
              >新增用户</el-button
            >
          </div>
        </el-col>
        <el-col :span="4">
          <div class="grid-content bg-purple">
            <el-button type="success" @click="getUserList">刷新</el-button>
          </div>
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table border stripe width="100%" :data="userList">
        <el-table-column fixed label="序号" prop="id"> </el-table-column>
        <el-table-column fixed label="姓名" prop="name"> </el-table-column>
        <el-table-column fixed label="用户名" prop="username">
        </el-table-column>
        <el-table-column fixed label="角色" prop="roles"> </el-table-column>
        <el-table-column fixed label="电话" prop="phone"> </el-table-column>
        <el-table-column fixed label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.locked"
              @change="lockedChanged(scope.row)"
              active-color="#ff4949"
              inactive-color=""
              active-text="锁定"
              inactive-text="激活"
            >
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column fixed label="操作" width="280">
          <template slot-scope="scope">
            <!-- 第一个是修改按钮 -->
            <el-tooltip
              effect="dark"
              content="授予角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-user"
                circle
                @click="editUserDialog(scope.row.id)"
              ></el-button>
            </el-tooltip>

            <!-- 第二个是解锁按钮 -->
            <el-tooltip
              effect="dark"
              content="手机号管理"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="success"
                icon="el-icon-phone-outline"
                circle
                @click="lockPhoneNumDialog(scope.row)"
              ></el-button>
            </el-tooltip>

            <!-- 第5个是解锁按钮 -->
            <el-tooltip
              effect="dark"
              content="查看用户详情"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="info"
                icon="el-icon-document-checked"
                circle
                @click="toShowUser(scope.row.id)"
              ></el-button>
            </el-tooltip>

            <!-- 第5个是解锁按钮 -->
            <el-tooltip
              effect="dark"
              content="删除用户"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                @click="removeUserDialog(scope.row.id)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.current"
        :page-sizes="[5, 10]"
        :page-size="queryInfo.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 删除用户对话框 -->
    <el-dialog
      title="删除用户"
      :visible.sync="removeUserDialogVisible"
      width="30%"
      center
    >
      <span>确定删除用户:{{ userForm.username }} 吗?</span>

      <span slot="footer" class="dialog-footer">
        <el-button @click="removeUserDialogVisible = false">关 闭</el-button>
        <el-button type="primary" @click="onRemoveUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addUserDialogVisible"
      width="50%"
      @close="addUserDialogClosed"
      center
    >
      <!-- 内容主体区 -->
      <el-form
        :model="addUser"
        :rules="addUserRules"
        ref="addUserRef"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUser.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="addUser.password"
            type="password"
            show-password
          ></el-input>
        </el-form-item>

        <el-form-item label="状态" prop="locked">
          <el-select v-model="addUser.locked">
            <el-option label="锁定" value="true"></el-option>
            <el-option label="激活" value="false"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSavaUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 绑定手机号码对话框 -->
    <el-dialog
      title="绑定手机号码"
      :visible.sync="lockPhoneNumDialogVisible"
      width="30%"
      center
      @close="lockPhoneDialogClosed"
    >
      <!-- 内容主体区 -->
      <el-form
        :model="lockPhoneNum"
        :rules="lockPhoneNumRules"
        ref="lockPhoneNumRef"
        label-width="100px"
      >
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="lockPhoneNum.phone" maxlength="11"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="lockPhoneNumDialogVisible = false">关 闭</el-button>
        <el-button type="primary" @click="onLockPhone">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 解除绑定手机号码对话框 -->
    <el-dialog
      title="解除绑定"
      :visible.sync="unlockPhoneNumDialogVisible"
      width="30%"
      center
    >
      <!-- 内容主体区 -->
      <span>确定解除手机号码吗?</span>
      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="unlockPhoneNumDialogVisible = false"
          >关 闭</el-button
        >
        <el-button type="primary" @click="onUnlockPhone">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户详情对话框 -->
    <el-dialog
      title=" 修改用户信息"
      :visible.sync="editUserDialogVisible"
      width="50%"
      center
    >
      <el-form :model="userForm" label-width="100px">
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="userForm.username"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input
            v-model="userForm.password"
            type="password"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item label="用户状态" prop="locked">
          <el-select v-model="userForm.locked">
            <el-option label="激活" value="false"> </el-option>
            <el-option label="锁定" value="true"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserDialogVisible = false">关 闭</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 查看用户详情对话框 -->
    <el-dialog
      title=" 查看用户信息"
      :visible.sync="showUserDialogVisible"
      width="50%"
      center
    >
      <el-form :model="checkUserForm" label-width="100px">
        <el-form-item label="编号" prop="no">
          <el-input v-model="checkUserForm.no" disabled></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="checkUserForm.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="学校" prop="school">
          <el-input v-model="checkUserForm.school" disabled></el-input>
        </el-form-item>
        <el-form-item label="学院" prop="college">
          <el-input v-model="checkUserForm.college" disabled></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="checkUserForm.phone" disabled></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-input v-model="checkUserForm.sex" disabled></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="locked">
          <el-input v-model="checkUserForm.locked" disabled></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="showUserDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>

    <!-- 锁定用户对话框 -->
    <!-- <el-dialog
      title="锁定用户"
      :visible.sync="lockUserDialogVisible"
      width="30%"
      center
    >
      <span>确定锁定用户吗?</span>

      <span slot="footer" class="dialog-footer">
        <el-button @click="disOnLockUser">关 闭</el-button>
        <el-button type="primary" @click="onLockUser">确 定</el-button>
      </span>
    </el-dialog> -->

    <!-- 解锁用户对话框 -->
    <!-- <el-dialog
      title="解锁用户"
      :visible.sync="unlockUserDialogVisible"
      width="30%"
      center
    >
      <span>确定激活用户吗?</span>

      <span slot="footer" class="dialog-footer">
        <el-button @click="disOnUnLockUser">关 闭</el-button>
        <el-button type="primary" @click="onUnLockUser">确 定</el-button>
      </span>
    </el-dialog> -->
  </div>
</template>

<script>
import {
  updateUser,
  getUser,
  pageUser,
  saveUser,
  removeUser,
  lockPhone,
  unlockPhone,
} from "@/api/usermanagement.js";
import { getDict } from "@/api/datadictionary.js";
export default {
  data() {
    var checkMobile = (rule, value, cb) => {
      const regMoblie =
        /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMoblie.test(value)) {
        return cb();
      }
      cb(new Error("请输入正确的手机号"));
    };
    return {
      //获取用户列表的参数对象
      queryInfo: {
        current: 1,
        size: 5,
        name: "",
      },
      total: 0,
      userList: [],
      //删除,查看详情，修改用户用户功能下获取用户整个对象
      userForm: {
        password: "",
        locked: "",
        username: "",
      },
      //增加用户的表单
      addUser: {
        username: "",
        password: "",
        locked: "true",
      },
      //增加用户表单的规则
      addUserRules: {
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
        ],
      },
      //绑定手机账号的对象
      lockPhoneNum: {
        userId: "",
        phone: "",
      },
      //绑定手机账号的对象规则
      lockPhoneNumRules: {
        phone: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            min: 11,
            max: 11,
            message: "请填写11位的手机号码",
            trigger: "blur",
          },
          {
            validator: checkMobile,
            trigger: "blur",
          },
        ],
      },
      //解除绑定手机账号的对象
      unlockPhoneNum: {
        userId: "",
        phone: "",
      },
      //解除手机账号绑定的规则
      unlockPhoneNumRules: {
        phone: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            min: 11,
            max: 11,
            message: "请填写11位的手机号码",
            trigger: "blur",
          },
          {
            validator: checkMobile,
            trigger: "blur",
          },
        ],
      },
      //展示用户详细信息功能显示与隐藏
      showUserDialogVisible: false,
      //修改用户详细信息功能显示与隐藏
      editUserDialogVisible: false,

      //新增用户功能显示与隐藏
      addUserDialogVisible: false,
      //绑定手机功能显示与隐藏
      lockPhoneNumDialogVisible: false,
      //解除手机绑定功能显示与隐藏
      unlockPhoneNumDialogVisible: false,
      //删除用户绑定功能显示与隐藏
      removeUserDialogVisible: false,
      //锁定用户显示与隐藏
      lockUserDialogVisible: false,
      //解锁用户显示与隐藏
      unlockUserDialogVisible: false,
      //查看专用对象
      checkUserForm: {},
      //性别列表
      sexList: [],
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.size = newSize;
      this.getUserList();
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.current = newPage;
      this.getUserList();
    },
    //显示用户的信息
    async getUserList() {
      const { data: res } = await pageUser(
        this.queryInfo.current,
        this.queryInfo.size
      );
      this.userList = res.data.records;
      this.total = res.data.total;
      this.userList.forEach((element) => {
        element.roles.forEach((role) => {
          if (role.flag == true) {
            element.roles = role.note;
          }
        });
      });
    },

    //获得性别列表
    async getSexList() {
      const { data: rest } = await getDict("sex");
      this.sexList = rest.data;
    },
    //查看用户详细信息
    checkUser(id) {
      getUser(id)
        .then((res) => {
          if (res.data.code !== 0) {
            return this.$message.error("查看失败");
          }
          this.checkUserForm = res.data.data;

          if (this.checkUserForm.locked == false) {
            this.checkUserForm.locked = "激活";
          } else {
            this.checkUserForm.locked = "锁定";
          }
          this.getSexList();
          console.log(this.sexList);
          this.sexList.forEach((sex) => {
            if (sex.code === this.checkUserForm.sex) {
              this.checkUserForm.sex = sex.info;
            }
          });
        })
        .catch(() => {
          this.$message.error("请求出错");
        });
    },
    //将弹窗显示出来
    toShowUser(id) {
      this.checkUser(id);
      this.showUserDialogVisible = true;
    },
    //将修改用户信息的弹窗显示出来
    editUserDialog(id) {
      localStorage.setItem("userId", JSON.stringify(id));
      this.$router.push("/user/role");
    },
    //将修改好的用户信息进行保存
    editUser() {
      var editForm = {
        locked: this.userForm.locked,
        password: this.userForm.password,
        username: this.userForm.username,
      };
      updateUser(this.userForm.id, editForm)
        .then((res) => {
          if (res.data.code !== 0) {
            return this.$message.error("保存失败");
          }
          this.editUserDialogVisible = false;
          this.getUserList();
        })
        .catch(() => {
          this.$message.error("请求出错");
        });
    },

    //重置新增用户填写的窗口
    addUserDialogClosed() {
      this.$refs.addUserRef.resetFields();
    },
    //点击保存已经填写好的账号
    onSavaUser() {
      var addUser = {
        username: this.addUser.username,
        locked: this.addUser.locked,
        password: this.addUser.password,
      };
      saveUser(addUser)
        .then((res) => {
          if (res.data.code !== 0) {
            return this.$message.error("请求失败！账户已存在");
          }
          this.addUserDialogVisible = false;
          this.getUserList();
        })
        .catch(() => {
          this.$message.error("请求出错");
        });
    },
    //绑定手机号码弹窗显示
    lockPhoneNumDialog(user) {
      if (user.phone == null) {
        this.lockPhoneNumDialogVisible = true;
        this.lockPhoneNum.userId = user.id;
      } else {
        this.unlockPhoneNumDialogVisible = true;
        this.unlockPhoneNum.userId = user.id;
      }
    },
    //解除绑定手机号码弹窗显示
    unlockPhoneNumDialog(user) {
      this.unlockPhoneNum.phone = user.phone;
      this.unlockPhoneNumDialogVisible = true;
    },
    //确认绑定手机号码
    onLockPhone() {
      var lockPhoneEntity = {
        userId: this.lockPhoneNum.userId,
        phone: this.lockPhoneNum.phone,
      };

      lockPhone(lockPhoneEntity.userId, lockPhoneEntity.phone)
        .then((res) => {
          if (res.data.code !== 0) {
            return this.$message.error("绑定失败！请检查已有手机号码");
          }
          this.lockPhoneNumDialogVisible = false;
          this.getUserList();
        })
        .catch(() => {
          this.$message.error("请求出错");
        });
    },

    //解除手机号码绑定
    onUnlockPhone() {
      unlockPhone(this.unlockPhoneNum.userId)
        .then((res) => {
          if (res.data.code !== 0) {
            return this.$message.error("解绑失败！请输入正确的手机号码");
          }
          this.unlockPhoneNumDialogVisible = false;
          this.getUserList();
        })
        .catch(() => {
          this.$message.error("请求出错");
        });
    },
    //清空绑定手机号码的表单
    lockPhoneDialogClosed() {
      this.$refs.lockPhoneNumRef.resetFields();
    },

    //获得修改用户的基本信息
    updateUserDialog(id) {
      getUser(id)
        .then((res) => {
          if (res.data.code !== 0) {
            return this.$message.error("请求出错");
          }
          this.editUserDialogVisible = true;
          var editOb = res.data.data;
          this.userForm = {
            id: editOb.id,
            username: editOb.username,
            password: editOb.password,
            locked: null,
          };
        })
        .catch(() => {
          this.$message.error("请求出错");
        });
    },
    //获取删除用户的基本信息
    removeUserDialog(id) {
      getUser(id)
        .then((res) => {
          if (res.data.code !== 0) {
            return this.$message.error("请求出错");
          }
          this.removeUserDialogVisible = true;
          this.userForm = res.data.data;
        })
        .catch(() => {
          this.$message.error("请求出错");
        });
    },
    //执行删除操作
    onRemoveUser() {
      removeUser(this.userForm.id)
        .then((res) => {
          if (res.data.code !== 0) {
            return this.$message.error("请求出错");
          }
          this.removeUserDialogVisible = false;
          this.getUserList();
        })
        .catch(() => {
          this.$message.error("请求出错");
        });
    },
    //执行用户锁switch操作
    lockedChanged(user) {
      if (user.locked == true) {
        //执行锁定操作
        var editForm = {
          locked: true,
          password: null,
          username: null,
        };
        updateUser(user.id, editForm)
          .then((res) => {
            if (res.data.code !== 0) {
              return this.$message.error("超级管理员无法锁定");
            }

            this.getUserList();
          })
          .catch(() => {
            this.$message.error("请求出错");
          });
      } else {
        //执行解锁操作
        var editForm = {
          locked: false,
          password: null,
          username: null,
        };
        updateUser(user.id, editForm)
          .then((res) => {
            if (res.data.code !== 0) {
              return this.$message.error("超级管理员无法锁定");
            }

            this.getUserList();
          })
          .catch(() => {
            this.$message.error("请求出错");
          });
      }
    },
  },
};
</script>

<style lang="less" scoped>
.breadcrumb {
  margin-bottom: 15px;
  font-size: 15px;
}
.box-card {
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15) !important;
}
.el-row-table {
  margin-bottom: 15px !important;
}
.el-pagination {
  margin-top: 15px;
}
</style>